<?php

namespace App\Http\Controllers\Business;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Http\Controllers\Controller;
use App\Models\Business\PlatformType;
use App\Models\Business\RecordDataColumn;
use Illuminate\Http\Request;

class RecordDataColumnController extends Controller
{
    use ModelSearchTrait;

    //
    public function index(Request $request, RecordDataColumn $dataColumn)
    {
        $dataColumn=$this->singleModelSearch($request,$dataColumn,$this->columnCondition());
        $columns=$dataColumn->with(['platformType'])->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success($columns);
    }
    //
    public function columnCondition()
    {
        return [
            ['platform_type_id','='],
        ];
    }

    //
    public function store(Request $request)
    {
        $platform=PlatformType::find($request->platform_type_id);
        if(empty($platform)){
            return $this->failed('平台类型id错误',201);
        }
        $data['platform_type_id']=$request->platform_type_id;
        $data=$this->columnData($request,$data);
        RecordDataColumn::create($data);
        return $this->success(['msg'=>'添加成功']);
    }
    //
    public function columnData($request,$data){
        for ($i=1;$i<=20;$i++){
            $column='custom_column'.$i;
            if($request->filled($column)){
                $data[$column]=mb_substr($request->$column,0,64);
            }else{
                $data[$column]=null;
            }
        }
        return $data;
    }

    //
    public function show(Request $request)
    {
        $show=RecordDataColumn::with(['platformType'])->find($request->record_id??0);
        return $this->success($show);
    }

    //
    public function update(Request $request)
    {
        $platform=PlatformType::find($request->platform_type_id);
        if(empty($platform)){
            return $this->failed('平台类型id错误',201);
        }
        $show=RecordDataColumn::find($request->record_id??0);
        if(empty($show)){
            return $this->failed('record_id错误',201);
        }
        $data['platform_type_id']=$request->platform_type_id;
        $data=$this->columnData($request,$data);
        $show->update($data);
        return $this->success(['msg'=>'编辑成功']);
    }

    //
    public function destroy(Request $request)
    {
        $show=RecordDataColumn::find($request->record_id??0);
        if(empty($show)){
            return $this->failed('record_id错误',201);
        }
        $show->delete();
        return $this->success(['msg'=>'删除成功']);
    }

    //
    public function getAllCustomColumns(){
        $records=RecordDataColumn::with(['platformType'])->get();
        return $this->success($records);
    }


}
